package com.sea.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sea.example.bean.CoordinateBean;
import com.sea.example.mapper.CoordinateMapper;
import com.sea.example.params.CoordinateListParam;
import com.sea.example.params.CoordinateParam;
import com.sea.example.service.CoordinateService;
import com.sea.example.service.CoordinateTimeService;
import com.sea.example.vo.CoordinateTimeVo;
import com.sea.example.vo.CoordinateVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Description: 坐标信息service
 * Author: hcxu
 * Time: 2024/9/5 2:46 PM
 */
@Service
@Slf4j
public class CoordinateServiceImpl extends ServiceImpl<CoordinateMapper, CoordinateVo> implements CoordinateService {
    @Autowired
    private CoordinateTimeService coordinateTimeService;

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "dataTransactionManager")
    public Boolean addCoordinateList(CoordinateListParam param) {
        List<CoordinateParam> coordinateParamList = param.getCoordinateParamList();
        Long time = param.getTime();
        List<CoordinateVo> voList = coordinateParamList.stream().map(dto -> {
            CoordinateVo vo = new CoordinateVo();
            BeanUtils.copyProperties(dto, vo);
            vo.setTime(time);
            return vo;
        }).collect(Collectors.toList());
        CoordinateTimeVo timeVo = new CoordinateTimeVo();
        timeVo.setTime(time);
        coordinateTimeService.save(timeVo);
        if(CollectionUtils.isNotEmpty(voList)){
            this.saveBatch(voList);
        }
        log.info("记录时间:{}",time);
        return true;
    }

    @Override
    public CoordinateBean getCoordinateByTime(Long time) {
        CoordinateBean resultBean = new CoordinateBean();
        List<CoordinateVo> list = this.list(new LambdaQueryWrapper<CoordinateVo>()
                .eq(CoordinateVo::getTime, time));
        List<Double> zList = list.stream().map(CoordinateVo::getZ).collect(Collectors.toList());
        Double heightSum = 0.0;
        for (Double aDouble : zList) {
            heightSum += aDouble;
        }
        resultBean.setHeight(String.valueOf(heightSum / zList.size()));
        resultBean.setCoordinateParamList(list);
        resultBean.setTime(time);
        return resultBean;
    }
}
